<?php
/**
 * Created by PhpStorm.
 * User: 六花
 * Date: 2019/4/27
 * Time: 17:20
 */

namespace Crontab\Controller;

use Think\Controller;


class IndexController extends Controller {
    public function index(){
        echo '123';
    }

    public function changeOrder(){
        $condOrder['add_time'] = array('elt',time()-30*60);
        $condOrder['status'] = 11;
        $res = M('order')->where($condOrder)->field('order_id')->select();
        $arr = array();
        if(!$res){
            return;
        }
        foreach ($res as $k => $v){
            array_push($arr, $v['order_id']);
        }
        $cond['order_id'] = array('in',$arr);
        M('order_extm')->startTrans();
        $res_extm = M('order_extm')->where($cond)->delete();
        if($res_extm === false){
            M('order_extm')->rollback();
            return false;
        }
        $res_goods = M('order_goods')->where($cond)->delete();
        if($res_goods === false){
            M('order_extm')->rollback();
            return false;
        }
        $res_order = M('order')->where($cond)->delete();
        if($res_order === false){
            M('order_extm')->rollback();
            return false;
        }
        M('order_extm')->commit();
        return true;
    }

    public function saveImages(){
        $res = M('save_images') -> where(array('is_save'=>0))->select();
        foreach ($res as $k =>$v){
            $path = '';
            if($v['type'] == 1 || $v['type'] == 3){
                $path = $_SERVER['DOCUMENT_ROOT'].'/data/files/store_'.$v['store_id'].'/goods_'.$v['goods_id'].'/';
            }else if($v['type'] == 2){
                $path = $_SERVER['DOCUMENT_ROOT'].'/data/files/store_'.$v['store_id'].'/goodsspec/';
            }
            try {
                $file_name = downloadImage($v['image_url'],$path,$v['type']);
            } catch (Exception $e) {
                continue;
            }

            $thumb_path = './../data/files/store_'.$v['store_id'].'/goods_'.$v['goods_id'].'/'.$file_name;
            $save_path = './../data/files/store_'.$v['store_id'].'/goods_'.$v['goods_id'].'/small_'.$file_name;
            if($v['type'] == 1){
                try {
                    make_thumb($thumb_path,$save_path);
                } catch (Exception $e) {
                    continue;
                }
            }
            $path_arr = explode('data',$path);
            $path_str = 'data'.$path_arr[2];
//            $thumb_arr = explode('data',$save_path);
            $thumb_str = 'data'.$path_arr[2];
            $send_data['id'] = $v['id'];
            $send_data['goods_id'] = $v['goods_id'];
            if($v['type'] == 2){
                $send_data['spec_id'] = $v['spec_id'];
            }else{
                $send_data['spec_id'] = 0;
            }
            $send_data['store_id'] = $v['store_id'];
            $send_data['file_name'] = $file_name;
            $send_data['file_path'] = $path_str.$file_name;
            $send_data['thumb_name'] = 'small_'.$file_name;
            $send_data['thumb_path'] = $thumb_str.'small_'.$file_name;
            try {
                save_sql($send_data,$v['type']);
            } catch (Exception $e) {
                continue;
            }
        }
    }

    public function createAccount(){
        $cond['ecm_order.status'] = array('IN','20,30,40');
        $first_day = strtotime(date('Y-m-1 00:00:00',strtotime('last month')));
        $last_day = strtotime(date('Y-m-d 23:59:59',strtotime(date('Y-m-1 23:59:59').' -1 day')));
        $cond['ecm_order.pay_time'] = array('between',array($first_day,$last_day));
        $res = M('order')->join('left join ecm_member on ecm_order.buyer_id = ecm_member.user_id')
                        ->join('left join ecm_store on ecm_member.s_id = ecm_store.store_id')
                        ->field('ecm_member.*,sum(ecm_order.order_amount) as order_amount')
                        ->group('ecm_member.user_id')
                        ->where($cond)
                        ->select();
        foreach($res as $key => $value){
            $res_account = M('account')->where(array('user_id'=>$value['user_id']))->order('start_time desc')->find();
            if(!$res_account){
                $account_num = 1  ;
            }else{
                $account_num = $res_account['account_num'] + 1;
            }
            $data['account_num'] = $account_num;
            $data['user_id'] = $value['s_id'];
            $data['start_time'] = $first_day;
            $data['end_time'] = $last_day;
            $data['money'] = $value['order_amount'];
            $data['state'] = 0;
            $res = M('account')->add($data);
            if(!$res){
                return false;
            }

        }
    }
}

//下载远程图片

function downloadImage($url,$path,$type)
{
    if(get_between($url,':','/')){
        $port = '80';
    }else{
        $port = get_between($url,':','/');
    }



    $ch = curl_init(); //curl_init(): 初始化一个新的会话，返回一个cURL句柄，供curl_setopt(), curl_exec()和curl_close() 函数使用。

    curl_setopt($ch, CURLOPT_URL, $url);//curl_setopt(): 设置一个cURL传输选项,

//CURLOPT_URL: 需要获取的 URL 地址，也可以在curl_init() 初始化会话的时候。

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //CURLOPT_RETURNTRANSFER: TRUE将curl_exec()获取的信息以字符串返回，而不是直接输出。

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);//CURLOPT_CONNECTTIMEOUT: 在尝试连接时等待的秒数。设置为0，则无限等待。

    curl_setopt($ch, CURLOPT_PORT, $port);

    $file = curl_exec($ch);//curl_exec(): 执行一个cURL会话

    curl_close($ch);//curl_close(): 关闭一个cURL会话

    $rs = mkdirs_1($path);

    $res = saveAsImage($url, $file, $path, $type);
    return $res;
}

//字符串截图某一位
function get_between($input, $start, $end) {
    $substr = substr($input, strlen($start)+strpos($input, $start),(strlen($input) - strpos($input, $end))*(-1));
    return $substr;
}

//type
// 1:商品主图

// 2:商品规格图

function saveAsImage($url, $file, $path ,$type = 1)
{
    $filenames = pathinfo($url, PATHINFO_BASENAME);//pathinfo(): 返回文件路径的信息
    $str=explode('.',$filenames);
    if($type == 2){
        $filename = 'spec_'.date("YmdHis").(time() % 200).rand(100000,999999).'.'.$str[1];
        $resource = fopen($path.$filename, 'a');//fopen(): 打开文件或url
    }else{
        $filename = date("YmdHis".(time()) % 200).rand(100000,999999).'.'.$str[1];
        $resource = fopen($path.$filename, 'a');//fopen(): 打开文件或url
    }
    $rs = fwrite($resource, $file);//fwrite(): 写入文件
    fclose($resource);//fclose(): 关闭一个已经打开的文件指针
    return $filename;
}

function mkdirs_1($path, $mode = 0777){
    if(is_dir($path)){
        return '无法创建,已经是目录了';
    }else{
        if(mkdir($path, $mode, true)) {
            return '创建成功';
        }else{
            return '创建失败';
        }
    }
}

//制作缩略图
function make_thumb($thumb_path,$save_path){
    $image = new \Think\Image();
    $image->open($thumb_path);
    $image->thumb(300, 300,\Think\Image::IMAGE_THUMB_FIXED)->save($save_path);
}

//存数据库(4张表)
function save_sql($data,$type){
    $file_model = M('uploaded_file');
    $goods_image_model = M('goods_image');
    $goods_model = M('goods');
    $goods_spec_model = M('goods_spec');
    $data_file = array();
    if($type == 1 || $type == 3){
        $data_file = array(
            'store_id'=>$data['store_id'],
            'file_type'=>'image/jpeg',
            'file_name'=>$data['file_name'],
            'file_path'=>$data['file_path'],
            'add_time'=> time(),
            'belong'=>2,
            'item_id'=>$data['goods_id']
        );
    }else{
        $data_file = array(
            'store_id'=>$data['store_id'],
            'file_type'=>'image/jpeg',
            'file_name'=>$data['file_name'],
            'file_path'=>$data['file_path'],
            'add_time'=> time(),
            'belong'=>6,
            'item_id'=>$data['goods_id']
        );
    }
    $res = $file_model->add($data_file);
    if(!$res){
        return '添加失败1';
    }
    if($type == 1){
        $data_image = array(
            'goods_id'=>$data['goods_id'],
            'image_url'=>$data['file_path'],
            'thumbnail'=>$data['thumb_path'],
            'file_id'=>$res
        );
        $res = $goods_image_model->add($data_image);
        if(!$res){
            return '添加失败2';
        }

    }
    if($type == 1){
        $data_goods = array(
            'default_image'=>$data['file_path'],
        );
        $res = $goods_model->where(array('goods_id'=>$data['goods_id']))->save($data_goods);
        if(!$res){
            return '添加失败3';
        }
    }

    if($type == 2){
        $data_goods_spec = array(
            'spec_1'=>$data['file_path'],
        );
        $res = $goods_spec_model->where(array('spec_id'=>$data['spec_id']))->save($data_goods_spec);
        if(!$res){
            return '添加失败4';
        }
    }

    if($type == 3){
        $res_description = M('goods')->where(array('goods_id'=>$data['goods_id']))->find();
        if(!$res_description){
            return '添加失败5';
        }
        if(!strstr($res_description['description'],'<p>')){
            $str = '<p><img src="./'.$data['file_path'].'"/></p>';
            $data_goods = array(
                'description'=>$str,
            );
        }else{
            $temp_str = str_replace('</p>','',$res_description['description']);
            $str = $temp_str.'<img src="./'.$data['file_path'].'"/></p>';
            $data_goods = array(
                'description'=>$str,
            );
        }
        $res = $goods_model->where(array('goods_id'=>$data['goods_id']))->save($data_goods);
        if(!$res){
            return '添加失败6';
        }
    }
    $res = M('save_images')->where(array('id'=>$data['id']))->save(array('is_save'=>1));
}